package com.wuyou.task;

import com.wuyou.common.utils.LogUtils;
import com.wuyou.commonredis.service.task.RankRunService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * @Author 幸福的甜蜜-kole
 * @Date 2017/9/28 10:24
 */
@Log4j
@Configuration
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private RankRunService rankRunService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent() == null) {
            LogUtils.info(log, "开机启动爬虫");
            try {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for(;true;){
                            try {
                                LogUtils.info(log, "启动爬虫");
                                rankRunService.spiderKeyword();
                            }catch (Exception ex){
                                ex.printStackTrace();
                                LogUtils.info(log, "爬虫执行错误: " + ex.getMessage());
                            }
                        }
                    }
                }).start();
            } catch (Exception e) {
                LogUtils.info(log, "开机启动爬虫: {0}", LogUtils.readErrMsg(e));
            }
        }
    }
}